package servlet;

import Dao.StudentDao;
import Impl.StudentDaoImpl;
import com.google.gson.Gson;
import model.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name = "/ListStudentServlet")
public class ListStudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");

        StudentDaoImpl studentDao = new StudentDao();
        List<Student> allstudent = null;
        try {
            allstudent = studentDao.getAllStudent();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        //将学生数据变为json数据
        Gson gson= new Gson();
        String students = gson.toJson(allstudent);
        PrintWriter out=response.getWriter();
        for(Student s : allstudent){
            System.out.println(s.toString());
        }
        out.write(students);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
